package com.qianda.qdminiapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qianda.qdminiapp.common.constant.CommonConstant;
import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.common.util.RandomUtil;
import com.qianda.qdminiapp.dao.account.QqdAccountDao;
import com.qianda.qdminiapp.dao.account.QqdAccountTradeDao;
import com.qianda.qdminiapp.dao.device.DeviceDao;
import com.qianda.qdminiapp.dao.device.QqdDeviceDao;
import com.qianda.qdminiapp.dao.device.QqdDeviceShareRateDao;
import com.qianda.qdminiapp.dao.device.QqdStoreDao;
import com.qianda.qdminiapp.dao.order.QqdOrderInfoDao;
import com.qianda.qdminiapp.dao.order.QqdOrderShareProfitDao;
import com.qianda.qdminiapp.dao.personmanage.QqdStaffDao;
import com.qianda.qdminiapp.dao.user.QqdUserBuyLimitDao;
import com.qianda.qdminiapp.dao.user.QqdUserDao;
import com.qianda.qdminiapp.domain.data.OrderTowalData;
import com.qianda.qdminiapp.domain.data.QqdStoreData;
import com.qianda.qdminiapp.domain.dto.OrderReturnDto;
import com.qianda.qdminiapp.domain.dto.PageRequest;
import com.qianda.qdminiapp.domain.model.account.QqdAccount;
import com.qianda.qdminiapp.domain.model.account.QqdAccountTrade;
import com.qianda.qdminiapp.domain.model.device.QqdDeviceShareRate;
import com.qianda.qdminiapp.domain.model.device.QqdStore;
import com.qianda.qdminiapp.domain.model.order.QqdOrderInfo;
import com.qianda.qdminiapp.domain.model.order.QqdOrderShareProfit;
import com.qianda.qdminiapp.domain.model.order.QqdOrderTowel;
import com.qianda.qdminiapp.dao.order.QqdOrderTowelDao;
import com.qianda.qdminiapp.domain.model.personmanage.QqdStaff;
import com.qianda.qdminiapp.domain.model.user.QqdUser;
import com.qianda.qdminiapp.domain.model.user.QqdUserBuyLimit;
import com.qianda.qdminiapp.service.OrderAndPaymentStrategy;
import com.qianda.qdminiapp.service.PaymentSelector;
import com.qianda.qdminiapp.service.QqdOrderTowelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianda.qdminiapp.service.ShareBenefitService;
import com.qianda.qdminiapp.service.order.BalancePaymentImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.server.InactiveGroupException;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 毛巾购买订单 服务实现类
 * </p>
 *
 * @author cw
 * @since 2019-08-14
 */
@Service
@Transactional
public class QqdOrderTowelServiceImpl extends ServiceImpl<QqdOrderTowelDao, QqdOrderTowel> implements QqdOrderTowelService {
    private static Logger LOGGER = LoggerFactory.getLogger(BalancePaymentImpl.class);

    @Autowired
    private QqdDeviceDao deviceDao;

    @Autowired
    private QqdOrderTowelDao qqdOrderTowelDao;

    @Autowired
    private QqdStoreDao qqdStoreDao;

    @Autowired
    private QqdStaffDao qqdStaffDao;

    @Autowired
    private QqdOrderInfoDao orderInfoDaoDao;

    @Autowired
    private QqdOrderShareProfitDao qqdOrderShareProfitDao;

    @Autowired
    private QqdAccountDao qqdAccountDao;

    @Autowired
    private QqdAccountTradeDao qqdAccountTradeDao;

    @Autowired
    private QqdUserDao qqdUserDao;

    @Autowired
    private QqdUserBuyLimitDao qqdUserBuyLimitDao;

    @Autowired
    private QqdDeviceShareRateDao qqdDeviceShareRateDao;

    @Override
    @Transactional
    public void orderRemoteReturn(OrderReturnDto orderReturnDto) {
        LOGGER.info("<<设备出巾命令返回>>: 开始上传返回结果");
        QueryWrapper<QqdOrderTowel> qqdOrderTowelQueryWrapper=new QueryWrapper<>();
        qqdOrderTowelQueryWrapper.eq("order_no",orderReturnDto.getOrderNo());
        QqdOrderTowel qqdOrderTowel = qqdOrderTowelDao.selectOne(qqdOrderTowelQueryWrapper);
        //订单不存在，不做处理
        if(qqdOrderTowel == null){
            return;
        }

        //修改库存
        Integer currentCount = qqdOrderTowel.getOrderCount()* qqdOrderTowel.getOrderDeviceLength();
        deviceDao.deviceTowelCountMinusOne(qqdOrderTowel.getOrderDeviceId(),qqdOrderTowel.getOrderCount(),currentCount);

        //修改订单状态为出巾完成
        qqdOrderTowel.setOrderStatus(CommonConstant.OrderOutTowelStatus.ORDER_OUT_TOWEL_STATUS_FINISH);
        qqdOrderTowel.setUpdateTime(LocalDateTime.now());
        qqdOrderTowelDao.updateById(qqdOrderTowel);
        LOGGER.info("<<设备出巾命令返回>>: 上传成功，设备出巾完成！");

        //用户改为非新用户
        QqdUser qqdUser = qqdUserDao.selectById(qqdOrderTowel.getOrderUserId());
        if(qqdUser.getIsNewUser() == CommonConstant.IsNewUser.IS_NEW_USER){
            QqdUser qqdUserNew  = new QqdUser();
            qqdUserNew.setId(qqdUser.getId());
            qqdUserNew.setIsNewUser(CommonConstant.IsNewUser.IS_NOT_NEW_USER);
            qqdUserDao.updateById(qqdUser);
        }

        //修改用户单日次数
        QqdStore qqdStore = qqdStoreDao.selectById(qqdOrderTowel.getStoreId());
        if(qqdStore.getIsPriceLimit()!=null &&   qqdStore.getIsPriceLimit() == CommonConstant.IsPriceLimit.IS_PRICE_LIMIT_YES){
            if(qqdOrderTowel.getOrderAmt().compareTo(qqdStore.getLimitPrice()) <0){
                QueryWrapper<QqdUserBuyLimit> qqdUserBuyLimitQueryWrapper = new QueryWrapper<>();
                qqdUserBuyLimitQueryWrapper.eq("user_id",qqdUser.getId());
                qqdUserBuyLimitQueryWrapper.eq("buy_date", LocalDate.now());
                QqdUserBuyLimit qqdUserBuyLimit = qqdUserBuyLimitDao.selectOne(qqdUserBuyLimitQueryWrapper);
                //为空创建，不为空则修改
                if(qqdUserBuyLimit == null){
                    QqdUserBuyLimit newUserBuyLimit = new QqdUserBuyLimit();
                    newUserBuyLimit.setUserId(qqdUser.getId());
                    newUserBuyLimit.setBuyDate(LocalDate.now());
                    newUserBuyLimit.setBuyTime(1);
                    qqdUserBuyLimitDao.insert(newUserBuyLimit);
                }else{
                    qqdUserBuyLimitDao.updateCount(qqdUser.getId(),LocalDate.now());
                }
                LOGGER.info("用户单日限制次数修改成功！");

            }
        }

        //订单分润
        sharBenefitStart(qqdOrderTowel);

    }

    @Override
    @Transactional
    public void orderRemoteErrorReturn(OrderReturnDto orderReturnDto) {
        LOGGER.info("<<设备出巾异常命令返回>>: 开始上传异常结果");
        QueryWrapper<QqdOrderTowel> qqdOrderTowelQueryWrapper=new QueryWrapper<>();
        qqdOrderTowelQueryWrapper.eq("order_no",orderReturnDto.getOrderNo());
        QqdOrderTowel qqdOrderTowel = qqdOrderTowelDao.selectOne(qqdOrderTowelQueryWrapper);
        //订单不存在，不做处理
        if(qqdOrderTowel == null){
            return;
        }

        Integer orderErrorType = null;
        String errorCode = orderReturnDto.getErrorCode();
        String code = errorCode.substring(0, 2);

        switch (Integer.valueOf(code)){
            //缺巾
            case 02:
                LOGGER.info("<<设备出巾异常命令返回>>: 缺巾");
                orderErrorType = 0;
                break;
             //卷巾处卡巾
            case 03:
                LOGGER.info("<<设备出巾异常命令返回>>: 卷巾处卡巾");
                orderErrorType = 3;
                break;
             //切巾电机异常
            case 04:
                LOGGER.info("<<设备出巾异常命令返回>>: 切巾电机异常");
                orderErrorType = 5;
                break;
             //切巾处卡巾
            case 05:
                LOGGER.info("<<设备出巾异常命令返回>>: 切巾处卡巾");
                orderErrorType=7;
                break;
             //IC卡模块错误
            case 06:
                LOGGER.info("<<设备出巾异常命令返回>>: IC卡模块错误");
                orderErrorType=9;
                break;
             //棉巾数量不足
            case 07:
                LOGGER.info("<<设备出巾异常命令返回>>: 棉巾数量不足");
                orderErrorType=11;
                break;
        }

        //订单状态改为出巾异常
        qqdOrderTowel.setOrderStatus(CommonConstant.OrderOutTowelStatus.ORDER_OUT_TOWEL_STATUS_ERROR);
        qqdOrderTowel.setOrderErrorType(orderErrorType);
        qqdOrderTowel.setUpdateTime(LocalDateTime.now());
        qqdOrderTowelDao.updateById(qqdOrderTowel);
        LOGGER.info("<<设备出巾异常命令返回>>: 上传成功");

        //发起退款
        OrderAndPaymentStrategy orderAndPaymentStrategy = PaymentSelector.getPaymentSelector(qqdOrderTowel.getOrderPayType());
        orderAndPaymentStrategy.refundPay(qqdOrderTowel);
    }

    @Override
    public IPage<OrderTowalData> findOrder(Long userId, PageRequest pageRequest) {
        IPage<OrderTowalData> orderTowalDataPage = new Page<>(pageRequest.getPage(),pageRequest.getSize());
        List<OrderTowalData> towalList = qqdOrderTowelDao.findTowalList(orderTowalDataPage, userId);
        orderTowalDataPage.setRecords(towalList);
        return orderTowalDataPage;
    }

    /*
     * 订单分润
     * @Description
     * @Author cw
     * @Date 17:41 2019/9/5
     * @Param [qqdOrderTowel]
     * @return void
     **/
    @Override
    public void sharBenefitStart(QqdOrderTowel qqdOrderTowel) {

        LOGGER.info("-------微信支付和零钱支付给各级代理商和门店，推荐人的分红-----------------------------");
        if(qqdOrderTowel.getOrderPayType() != CommonConstant.PayType.PAY_TYPE_WX  && qqdOrderTowel.getOrderPayType() != CommonConstant.PayType.PAY_TYPE_BALANCE){
            return ;
        }
        //获取门店
        QqdStore qqdStore = qqdStoreDao.selectById(qqdOrderTowel.getStoreId());
        if(qqdStore != null){
            //省级代理商
            QqdStaff provinceAgent = qqdStaffDao.selectById(qqdStore.getProvinceAgentId());

            //城市合伙人
            QqdStaff cityPartner = qqdStaffDao.selectById(qqdStore.getCityPartnerId());

            //服务商
            QqdStaff servcie = qqdStaffDao.selectById(qqdStore.getServiceProviderId());

            //门店负责人
            QqdStaff principal = qqdStaffDao.selectById(qqdStore.getPrincipalId());

            //省级代理商分润
            BigDecimal provinceAgentAmt = BigDecimal.ZERO;
            //城市合伙人分润
            BigDecimal cityPartnerAmt = BigDecimal.ZERO;
            //服务商分润
            BigDecimal servcieAmt = BigDecimal.ZERO;
            //门店分润
            BigDecimal principalAmt = BigDecimal.ZERO;

            //获取设备关联的分润比
//            QueryWrapper<QqdDeviceShareRate> qqdDeviceShareRateQueryWrapper = new QueryWrapper<>();
//            qqdDeviceShareRateQueryWrapper.eq("device_id",qqdOrderTowel.getOrderDeviceId());
//            QqdDeviceShareRate qqdDeviceShareRate = qqdDeviceShareRateDao.selectOne(qqdDeviceShareRateQueryWrapper);

            //省代理商分润比
            BigDecimal privinceRate = BigDecimal.ZERO;
            //城市合伙人分润比
            BigDecimal cityRate = BigDecimal.ZERO;
            //服务人员分润比
            BigDecimal serviceRate = BigDecimal.ZERO;
            //门店老板分润比
            BigDecimal storeRate = BigDecimal.ZERO;

           // if(qqdDeviceShareRate != null){
                privinceRate=provinceAgent.getShareBenefitRate();
                cityRate = cityPartner.getShareBenefitRate();
                serviceRate =  servcie.getShareBenefitRate();
                storeRate = principal.getShareBenefitRate();
           // }

            if(provinceAgent != null && provinceAgent.getShareBenefitRate() != null){
                provinceAgentAmt = privinceRate.multiply(new BigDecimal("0.01")).multiply(qqdOrderTowel.getOrderAmt()).setScale(2,BigDecimal.ROUND_HALF_UP);
            }

            if(cityPartner != null && cityPartner.getShareBenefitRate() != null){
                cityPartnerAmt = cityRate.multiply(new BigDecimal("0.01")).multiply(qqdOrderTowel.getOrderAmt()).setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            if(servcie != null && servcie.getShareBenefitRate() != null){
                servcieAmt =  serviceRate.multiply(new BigDecimal("0.01")).multiply(qqdOrderTowel.getOrderAmt()).setScale(2,BigDecimal.ROUND_HALF_UP);
            }

            if(principal != null && principal.getShareBenefitRate() != null){
                principalAmt =  storeRate.multiply(new BigDecimal("0.01")).multiply(qqdOrderTowel.getOrderAmt()).setScale(2,BigDecimal.ROUND_HALF_UP);
            }

            //如果分润比都为0，则不创建分润订单
//            if(provinceAgentAmt.compareTo(BigDecimal.ZERO) == 0   &&  cityPartnerAmt.compareTo(BigDecimal.ZERO) == 0
//                    && servcieAmt.compareTo(BigDecimal.ZERO)==0  && principalAmt.compareTo(BigDecimal.ZERO) == 0){
//                return;
//            }


            LOGGER.info("开始创建订单");
            String orderNo = RandomUtil.getId();
            //创建订单主表
            QqdOrderInfo qqdOrderInfo = new QqdOrderInfo();
            qqdOrderInfo.setOrderNo(orderNo);
            qqdOrderInfo.setOrderUserId(qqdOrderTowel.getOrderUserId());
            qqdOrderInfo.setOrderType(CommonConstant.QqdOrderType.QQD_ORDER_TYPE_SHAW_BENEFIT);
            qqdOrderInfo.setOrderTime(LocalDateTime.now());
            qqdOrderInfo.setOrderAmt(qqdOrderTowel.getOrderAmt());
            qqdOrderInfo.setOrderRealAmt(qqdOrderTowel.getOrderAmt());
            qqdOrderInfo.setStatus(CommonConstant.Status.STATUS_NORMAL);
            qqdOrderInfo.setCreateTime(LocalDateTime.now());
            orderInfoDaoDao.insert(qqdOrderInfo);

            //创建分润表
            QqdOrderShareProfit qqdOrderShareProfit = new QqdOrderShareProfit();
            qqdOrderShareProfit.setCompanyId(qqdOrderTowel.getCompanyId());
            qqdOrderShareProfit.setOrderTowelId(qqdOrderTowel.getId());
            qqdOrderShareProfit.setOrderUserId(qqdOrderTowel.getOrderUserId());
            qqdOrderShareProfit.setDeviceId(qqdOrderTowel.getOrderDeviceId());
            qqdOrderShareProfit.setOrderAmt(qqdOrderTowel.getOrderAmt());
            qqdOrderShareProfit.setOrderPayTime(qqdOrderTowel.getOrderPayTime());
            if(provinceAgent !=null){
                qqdOrderShareProfit.setProvinceAgentId(provinceAgent.getId());
                qqdOrderShareProfit.setProvinceAgentName(provinceAgent.getName());
                qqdOrderShareProfit.setShareProfitProvince(provinceAgentAmt);
            }
            if(cityPartner != null){
                qqdOrderShareProfit.setCityPartnerId(cityPartner.getId());
                qqdOrderShareProfit.setCityPartnerName(cityPartner.getName());
                qqdOrderShareProfit.setShareProfitCity(cityPartnerAmt);
            }

            if(servcie != null){
                qqdOrderShareProfit.setServiceProviderId(servcie.getId());
                qqdOrderShareProfit.setServiceName(servcie.getName());
                qqdOrderShareProfit.setShareProfitService(servcieAmt);
            }

            if(principal != null){
                qqdOrderShareProfit.setShareProfitStorePrincipalId(principal.getId());
                qqdOrderShareProfit.setShareProfitStorePrincipal(principal.getName());
                qqdOrderShareProfit.setShareProfitStoreAmt(principalAmt);
            }
            qqdOrderShareProfitDao.insert(qqdOrderShareProfit);

            addAccountAmt(provinceAgent,provinceAgentAmt);
            addAccountAmt(cityPartner,cityPartnerAmt);
            addAccountAmt(servcie,servcieAmt);
            addAccountAmt(principal,principalAmt);
        }

    }

    private void addAccountAmt(QqdStaff staff, BigDecimal amt){
        if(staff != null){
            QueryWrapper<QqdAccount> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("staff_id",staff.getId()).eq("status",CommonConstant.Status.STATUS_NORMAL);
            QqdAccount qqdAccount = qqdAccountDao.selectOne(accountQueryWrapper);
            if(qqdAccount == null){
                throw new SimpleException(ExceptionCode.EX_HTTP_INPUT_NOT_ENTATY);
            }
            qqdAccountDao.addBalance(qqdAccount.getId(), amt, qqdAccount.getBalance());

            //新增一条交易明细
            QqdAccountTrade qqdAccountTrade = new QqdAccountTrade();
            qqdAccountTrade.setStaffId(staff.getId());
            qqdAccountTrade.setAccountId(qqdAccount.getId());
            qqdAccountTrade.setTradeType(CommonConstant.TradeType.TRADE_TYPE_SHARE);
            qqdAccountTrade.setTradeState(CommonConstant.TradeState.TRADE_STATE_IN);
            //  qqdAccountTrade.setTradeMode(CommonConstant.TradeMode.TRADE_MODEL_WALLET);
            qqdAccountTrade.setTradeTime(LocalDateTime.now());
            qqdAccountTrade.setTradeBeforeAmt(qqdAccount.getBalance());
            qqdAccountTrade.setTradeAmt(amt);
            qqdAccountTrade.setStatus(CommonConstant.Status.STATUS_NORMAL);
            qqdAccountTrade.setCreateTime(LocalDateTime.now());
            qqdAccountTradeDao.insert(qqdAccountTrade);
        }
    }

}
